跳到主要内容

07. Alias

别名是字段的另一个名称,用于序列化和反序列化数据。

你可以通过以下方式指定别名:

For examples of how to use alias, validation_alias, and serialization_alias, see Field aliases.

AliasPath and AliasChoices

Pydantic provides two special types for convenience when using validation_aliasAliasPath and AliasChoices.

AliasPath 指定某字段的路径来建立别名

from pydantic import BaseModel, Field, AliasPath

class User(BaseModel):
first_name: str = Field(validation_alias=AliasPath('names', 0))
last_name: str = Field(validation_alias=AliasPath('names', 1))

user = User.model_validate({'names': ['John', 'Doe']})
print(user)
#> first_name='John' last_name='Doe'

AliasChoices 指定多个字段作为别名

from pydantic import BaseModel, Field, AliasChoices

class User(BaseModel):
first_name: str = Field(validation_alias=AliasChoices('first_name', 'fname'))
last_name: str = Field(validation_alias=AliasChoices('last_name', 'lname'))

user = User.model_validate({'fname': 'John', 'lname': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'
user = User.model_validate({'first_name': 'John', 'lname': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'

当然这俩能合在一起用

from pydantic import BaseModel, Field, AliasPath, AliasChoices


class User(BaseModel):
first_name: str = Field(validation_alias=AliasChoices('first_name', AliasPath('names', 0)))
last_name: str = Field(validation_alias=AliasChoices('last_name', AliasPath('names', 1)))


user = User.model_validate({'first_name': 'John', 'last_name': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'
user = User.model_validate({'names': ['John', 'Doe']})
print(user)
#> first_name='John' last_name='Doe'
user = User.model_validate({'names': ['John'], 'last_name': 'Doe'})
print(user)
#> first_name='John' last_name='Doe'

alias generator

使用 Config 的  alias_generator 参数来设置批量 alias 生成逻辑

This is useful if you want to use a consistent naming convention for all fields in a model, but don't want to specify the alias for each field individually.

Note: Pydantic offers three built-in alias generators that you can use out of the box:

* [`to_pascal`][pydantic.alias_generators.to_pascal]
* [`to_camel`][pydantic.alias_generators.to_camel]
* [`to_snake`][pydantic.alias_generators.to_snake]

Using a callable

from pydantic import BaseModel, ConfigDict


class Tree(BaseModel):
model_config = ConfigDict(
alias_generator=lambda field_name: field_name.upper()
)

age: int
height: float
kind: str


t = Tree.model_validate({'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'})
print(t.model_dump(by_alias=True))
#> {'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'}

Using an AliasGenerator

You can use an AliasGenerator to specify different alias generators for validation and serialization.

This is particularly useful if you need to use different naming conventions for loading and saving data, but you don't want to specify the validation and serialization aliases for each field individually.

from pydantic import AliasGenerator, BaseModel, ConfigDict


class Tree(BaseModel):
model_config = ConfigDict(
alias_generator=AliasGenerator(
validation_alias=lambda field_name: field_name.upper(),
serialization_alias=lambda field_name: field_name.title(),
)
)

age: int
height: float
kind: str


t = Tree.model_validate({'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'})
print(t.model_dump(by_alias=True))
#> {'Age': 12, 'Height': 1.2, 'Kind': 'oak'}

别名的优先级

如果在字段上指定了别名,它将默认优先于由别名生成器生成的别名。

from pydantic import BaseModel, ConfigDict, Field


def to_camel(string: str) -> str:
return ''.join(word.capitalize() for word in string.split('_'))


class Voice(BaseModel):
model_config = ConfigDict(alias_generator=to_camel)

name: str
language_code: str = Field(alias='lang')


voice = Voice(Name='Filiz', lang='tr-TR')
print(voice.language_code)
#> tr-TR
print(voice.model_dump(by_alias=True))
#> {'Name': 'Filiz', 'lang': 'tr-TR'}

You may set alias_priority on a field to change this behavior:

  • alias_priority=2 the alias will not be overridden by the alias generator.
  • alias_priority=1 the alias will be overridden by the alias generator.
  • alias_priority not set:
    • alias is set: the alias will not be overridden by the alias generator.
    • alias is not set: the alias will be overridden by the alias generator.

The same precedence applies to validation_alias and serialization_alias. See more about the different field aliases under field aliases.